package com.concurrency.example.sync;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

@Slf4j
public class SyncExample1 {
    /**
     * 修饰代码块
     */
    public void test1(int threadNumber, String objName){
        synchronized (this){

            for (int i = 0; i < 10; i++) {
                log.info("test1:调用对象{}-线程{}-{}",objName,threadNumber,i);
            }

        }
    }

    /**
     * 修饰方法
     */
    public synchronized void test2(int threadNumber,String objName){

        for (int i = 0; i < 10; i++) {
            log.info("test2:调用对象{}-线程{}-{}",objName,threadNumber,i);
        }
    }

    public static void main(String[] args) {
        SyncExample1 se = new SyncExample1();
        //这里采用线程池创建线程，模拟多线程同时执行
        Executor executor = Executors.newCachedThreadPool();
        //对于同一个对象，锁有效
        executor.execute(()->{se.test1(1,"对象se");});
        executor.execute(()->{se.test1(2,"对象se");});

        //对于两个对象
        SyncExample1 se2 = new SyncExample1();
        executor.execute(()->{se2.test1(1,"对象se2");});
        executor.execute(()->{se2.test1(2,"对象se2");});

        /**
         * 通过结果可以看见：修饰代码块，修饰方法的作用范围是同一个对象；多个对象互不影响。
         */

    }
}
